package file;

import java.io.*;
import java.util.*;

public class AggiornamentoSelettivo {

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		System.out.println("Nome file=");
		String nome = sc.nextLine();
		System.out.println("Intero da aggiungere");
		int x = sc.nextInt();
		inserisci(nome, x);

	}

	private static void inserisci(String nome, int x) throws IOException {
		RandomAccessFile raf = new RandomAccessFile(nome, "r");
		DataOutputStream tmp = new DataOutputStream(new FileOutputStream("tmp"));
		long pos = 0;
		int y = 0;
		boolean flag = false;
		while (pos < raf.length() && !flag) {
			y = raf.readInt();
			if (y > x)
				flag = true;
			else {
				tmp.writeInt(y);
				pos = raf.getFilePointer();
			}

		}// while
		tmp.writeInt(x);
		if(flag){
			for(;;){
				tmp.writeInt(x);
				pos=raf.getFilePointer();
				if(pos==raf.length())
					break;
				y=raf.readInt();
				
			}//for
			if(flag)
				tmp.close();raf.close();
		}
	}

}
